package com.ys.utils.base.http;

import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Cookie基本操作，简写 日后弥补
 * 
 * @author yunpeng@xiu8.com
 */
public class CookieHandler {

	/**
	 * 设置Cookie
	 * 
	 * @param key
	 * @param value
	 * @param seconds
	 *            秒为单位
	 * @param equalDomain  需要匹配的Domain
	 * @param defaultDomain  默认的Domain
	 * @param req 
	 * @param resp 
	 */
	public static void setCookie(String key, String value, int seconds, boolean rember, String equalDomain, String defaultDomain, HttpServletRequest req, HttpServletResponse resp) {
		String domain = getDoMain(req, equalDomain, defaultDomain);
		setCookie(domain, key, value, seconds, rember,resp);
	}

	/**
	 * 设置Cookie
	 * 
	 * @param key
	 * @param value
	 *            永久Cookie
	 * 
	 *            修改cookie存储时间 原来时间为-1有问题，现在修改为5年 修改人xushufei
	 * @param equalDomain  需要匹配的Domain
	 * @param defaultDomain  默认的Domain
	 * @param req 
	 * @param resp 
	 */
	public static void setCookie(String key, String value, boolean rember, String equalDomain, String defaultDomain, HttpServletRequest req, HttpServletResponse resp) {
		setCookie(key, value, 60 * 60 * 24 * 30 * 12 * 5, rember,equalDomain,defaultDomain,req,resp);
	}

	/**
	 * 设置Cookie
	 * 
	 * @param key
	 * @param value
	 * @param seconds
	 *            秒为单位
	 */
	public static void setCookie(String domain, String key, String value, int seconds, boolean rember,HttpServletResponse resp) {
		try {
			Cookie cookie = new Cookie(key, value);
			if (rember) {
				cookie.setMaxAge(seconds);
			}
			cookie.setPath("/");
			cookie.setDomain(domain);
			resp.addCookie(cookie);
		} catch (Exception e) {
			Logger.error("设置Cookie失败", e);
		}

	}

	/**
	 * 获取Cookie
	 * 
	 * @param key
	 *            根据Key
	 * @return
	 */
	public static String getCookie(String key,HttpServletRequest req) {
		try {
			String cookieStr = req.getHeader("cookie");
			String val = null;
			if (!StringHandler.isEmpty(cookieStr)) {
				String[] cookievalues = cookieStr.split(";");
				if (cookievalues != null && cookievalues.length > 0) {
					for (int j = 0; j < cookievalues.length; j++) {
						if (cookievalues[j].indexOf("=") > 0) {
							String keyPair = cookievalues[j].substring(0, cookievalues[j].indexOf("=")).trim();
							if (keyPair.equals(key)) {
								val = cookievalues[j].substring(cookievalues[j].indexOf("=") + 1).trim();
								if (val.startsWith("\"")) {
									val = val.substring(1, val.length() - 1);
								}
								break;
							}
						}
					}
				}
			}
			if (StringHandler.isEmpty(val)) {
				Cookie[] cookies = req.getCookies();
				if (cookies == null) {
					return null;
				}
				for (int i = 0; i < cookies.length; i++) {
					Cookie cookie = cookies[i];
					if (cookie.getName().equals(key)) {
						val = cookie.getValue();
						break;
					}
				}
			}
			return val;
		} catch (Exception e) {
			Logger.error("获取Cookie失败", e);
		}
		return "";
	}

	/**
	 * 根据request获取domain，如果满足以下条件，返回默认的domain，否则返回request获取的domain
	 * 1.request获取的domain为空
	 * 2.request获取的domain为"webserver"
	 * 3.request获取的domain与equalDomain相同
	 * 4.request获取的domain包含tieba.xiu8.com 贴吧域下
	 * 5.request获取的domain不包含"xiu8.com"
	 */
	public static String getDoMain(HttpServletRequest req, String equalDomain, String defaultDomain) {
		String domain = req.getServerName();
		Logger.info("getDoMain:" + domain);
		if ("webserver".equals(domain) || StringHandler.isEmpty(domain)) {
			domain = defaultDomain;
//			domain = "xiu8.com";
		} else {
			if (domain.equals(equalDomain)) {
				domain = defaultDomain;
//				domain = "xiu8.com";
			}
		}
		//贴吧充值，添加此判断。将其cookie作用域同秀吧主站一致
		domain = domain.indexOf("tieba.xiu8.com") >=0 ? defaultDomain : domain;
		
		domain = domain.indexOf(defaultDomain) < 0 ? defaultDomain : domain;
		return domain;
	}

}
